//
//  ViewController.m
//  999-考勤定位
//
//  Created by 李晓东 on 2018/4/7.
//  Copyright © 2018年 PeanutXu. All rights reserved.
//

#import "ViewController.h"
#import "LocationManager.h"
#import "DatabaseManager.h"
//#import "KeepaliveManager.h"
#import "Tools.h"

#import "_99_考勤定位-Swift.h"
#import <MapKit/MapKit.h>

typedef enum {
    Sunday = 1,
    Monday = Sunday << 1,
    Tuesday = Monday << 1,
    Wednesday = Tuesday << 1,
    Thursday = Wednesday << 1,
    Friday = Thursday << 1,
    Saturday = Friday << 1
} WorkdayEnum;

@interface ViewController ()
@property (weak, nonatomic) IBOutlet MKMapView *mapView;
@property (nonatomic, strong) GetLocationRuleBlock getLocationRuleBlock;
@property (weak, nonatomic) IBOutlet UISwitch *switchView;

@property (nonatomic, strong) UISwitch *ownSwitch;
@end

@implementation ViewController{
    NSInteger _weekday;
    LocalNotification *_locationNotification;
    
}
static BOOL isCalledBackgroundThread = NO;
static BOOL located = NO;
static NSTimer *timer;
- (void)viewDidLoad {
    [super viewDidLoad];
    [self listenerWeekday];
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(updateLocationSetting:) name:@"ChangeNotificationSetting" object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(applicationDidEnterBackground:) name:UIApplicationDidEnterBackgroundNotification object:nil];
    
    self.ownSwitch = [[UISwitch alloc]initWithFrame:CGRectMake(50, 50, 120, 60)];
    
    [self.view addSubview:self.ownSwitch];
    
    _locationNotification = [[LocalNotification alloc]init];
    UIApplication *application = [_locationNotification initLocalNotification];
    UILocalNotification *localNotification = [_locationNotification createLocalNoti];
    
}

- (void)updateLocationSetting:(NSNotification *)notification {
    
    _weekday = [notification.userInfo[@"weekday"] integerValue];
    NSLog(@"done");
}

- (IBAction)locatedSettingClick:(id)sender {
    id controller = [self.storyboard instantiateViewControllerWithIdentifier:@"LocatedSettingController"];
//    [self presentViewController:controller animated:YES completion:nil];
    [self showViewController:controller sender:nil];
    
}

- (void)applicationDidEnterBackground:(NSNotification *)notification {
    // 定位中,就不需要启动后台线程了
//    if (!isCalledBackgroundThread) {
//        KeepaliveManager *keepaliveManager = [KeepaliveManager shareManager];
//        [keepaliveManager callBackgroundTask];
//        isCalledBackgroundThread = YES;
//    }
//
////    [self performSelector:@selector(callBackthread) withObject:nil afterDelay:60 * 0.5];
//
////    timer = [NSTimer scheduledTimerWithTimeInterval:60 * 1 target:self selector:@selector(callBackthread) userInfo:nil repeats:YES];
    

}

- (void)listenerWeekday {
    DatabaseManager *databaseManager = [DatabaseManager shareDatabaseManager];
    //        __weak typeof(self) weakself = self;
    [databaseManager setGetLocationRuleBlock:^(NSArray *array) {
        NSDictionary *dict = array.lastObject;
        _weekday = [dict[@"weekday"] integerValue];
        
        if ([dict[@"off_hour"] integerValue] - [dict[@"office_hour"] integerValue] > 0) {

            dispatch_async(dispatch_get_global_queue(0, 0), ^{
                [self runloop:[dict[@"office_hour"] integerValue] and:[dict[@"off_hour"] integerValue] andWeekday:&_weekday];
                
            });
            
        }
    }];
    [databaseManager queryInLocationRule];

}

// 这个方法暂时不考虑通宵工作,即跨越2天的情况
- (void)runloop:(NSInteger)officeHour and:(NSInteger)offHour andWeekday:(NSInteger *)weekday {
    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
    [formatter setDateFormat:@"HH:mm"];
//    static BOOL located = NO;
    static BOOL stopLocated = NO;
    while (true) {
        WorkdayEnum workdayEnum = [self getSomething:[self getNowWeekday]];
        // 判断今天是否在工作日.大于0就是工作日
        int flag = [self enumToWeekday:*weekday andToday:workdayEnum];
        NSString *currentDateStr = [formatter stringFromDate:[NSDate date]];
        NSInteger currentSeconds = [Tools transformInSeconds:currentDateStr];
        // 循环监听是否已经在上班状态,上班状态即开始定位
        if (currentSeconds >= officeHour && currentSeconds <= offHour && !located && flag > 0) {
//            [self callBackthread];
            // 当你是用子线程来监听是否到了定位时间段,那么这时,你就需要在主线程中调用定位的方法.否则,在子线程中调用,还不知道什么时候才会执行
            dispatch_async(dispatch_get_main_queue(), ^{
                [_locationNotification sendNotificationWithContent:@"终于开始了"];
                
                [self.switchView setOn:YES animated:YES];
                LocationManager *locationManager = [LocationManager shareLocationManager];
                [locationManager startLocating];
                
                if (timer) {
                    [timer invalidate];
                    timer = nil;
                }
            });
            // 定位中
            located = YES;
            stopLocated = NO;
            isCalledBackgroundThread = NO;
            [NSThread sleepForTimeInterval:(60 * 2)];

        } else if (flag == 0 || currentSeconds > offHour || (currentSeconds < (officeHour - 0 * 60)) || located) {
//            [_locationNotification sendNotificationWithContent:@"长寿中"];

            if (!stopLocated && (currentSeconds > offHour || currentSeconds < officeHour)) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    [self.switchView setOn:NO animated:YES];
                    LocationManager *locationManager = [LocationManager shareLocationManager];
                    [locationManager stopLocating];
                    NSLog(@"考勤定位结束");
                    
                });
                stopLocated = YES;
                located = NO;
                
            }
            [NSThread sleepForTimeInterval:(60 * 2)];

        } else if (currentSeconds >= (officeHour - 2 * 60) && currentSeconds < officeHour) {
            
            [NSThread sleepForTimeInterval:30];
        }
        // 这里应该有个心跳包,给到后台.证明现在的位置信息是有效的
        [self heartBeat];
    }
}



- (void)heartBeat {
    NSLog(@"我是线程--%@", [NSThread currentThread]);
    [HeartBeatManager heartbeat];
//    timer = [NSTimer timerWithTimeInterval:60 * 2 repeats:YES block:^(NSTimer * _Nonnull timer) {
//        KeepaliveManager *keepaliveManager = [KeepaliveManager shareManager];
//        [keepaliveManager callBackgroundTask];
//        NSLog(@"开启后台服务");
//        [_locationNotification sendNotificationWithContent:@"开启后台定位"];
//
//    }];
//
//    [[NSRunLoop currentRunLoop]addTimer:timer forMode:NSRunLoopCommonModes];
        
//    KeepaliveManager *keepaliveManager = [KeepaliveManager shareManager];
//    [keepaliveManager callBackgroundTask];
    
//    [self performSelector:@selector(callBackthread) withObject:nil afterDelay:60 * 1];
}

- (int)enumToWeekday:(int)weekday andToday:(WorkdayEnum)today{

    int length = 0;
    if (weekday == 1)  {
        length = 1;
    } else if (weekday >= 2 && weekday < 4) {
        length = 2;
    } else if (weekday >= 4 && weekday < 8) {
        length = 4;
    } else if (weekday >= 8 && weekday < 16) {
        length = 8;
    } else if (weekday >= 16 && weekday < 32) {
        length = 16;
    } else if (weekday >= 32 && weekday < 64) {
        length = 32;
    } else if (weekday >= 64) {
        length = 64;
    }
    
    if (length == today) {
        return length;
    } else if (length < today) {
        return 0;
    }
    
    return [self enumToWeekday:weekday - length andToday:today];
}

// 获取今天星期几
- (NSInteger)getNowWeekday {
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierChinese];
    NSDateComponents *comps = [[NSDateComponents alloc] init];
    NSInteger unitFlags = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitWeekday | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;
    NSDate *now = [NSDate date];
    // 话说在真机上需要设置区域，才能正确获取本地日期，天朝代码:zh_CN
//    calendar.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"zh_CN"];
    comps = [calendar components:unitFlags fromDate:now];
    return [comps weekday];
}

- (WorkdayEnum)getSomething:(NSInteger)weekday{
    WorkdayEnum workday;
    switch (weekday) {
        case 1:
            workday = Sunday;
            break;
        case 2:
            workday = Monday;
            break;
        case 3:
            workday = Tuesday;
            break;
        case 4:
            workday = Wednesday;
            break;
        case 5:
            workday = Thursday;
            break;
        case 6:
            workday = Friday;
            break;
        case 7:
            workday = Saturday;
            break;
        default:
            break;
    }
    return workday;
}
- (IBAction)switchSlide:(id)sender {
    [self.switchView isOn] ? [self listenerWeekday] : nil;
}
@end
